<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Extract extends Model
{
    const CREATED_AT = 'insert_time';
    const UPDATED_AT = 'update_time';
    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'lexiang_extract';

    protected $primaryKey = 'extract_id';

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = [
    	'users_id','amount',
    	'bank_id','extract_status',
    	'extract_desc','extract_time',
    	'extract_mouth','company_id',
    	'insert_time','update_time'
    ];

    public $timestamps = true;
    /**
     * @param \DateTime|int $value
     * @return false|int
     * @author dividez
     */
    public function fromDateTime($value){
        return strtotime(parent::fromDateTime($value));
    }

    /**
     * 商户提现列表
     */
    public function shoplist($shopid=false,$page=15)
    {
        return  Extract::where('lexiang_extract.extract_mouth',1)
        ->where(function($q)use($shopid){
            if(!empty(session('company_id'))){
                $q = $q->where('lexiang_extract.company_id',session('company_id'));
            }
            if($shopid){
                $q = $q->where('lexiang_extract.users_id',$shopid);
            }
            return $q;
        })
        ->leftJoin('lexiang_bankcard','lexiang_bankcard.bank_id','=','lexiang_extract.bank_id')
        ->leftJoin('lexiang_meal_shop','lexiang_meal_shop.users_id','=','lexiang_extract.users_id')
        ->leftJoin('lexiang_meal_company','lexiang_meal_company.company_id','=','lexiang_extract.company_id')
        ->select('lexiang_extract.*','lexiang_bankcard.bank_number','lexiang_bankcard.openbank','lexiang_bankcard.bank_name','lexiang_meal_shop.shop_name','lexiang_meal_shop.shop_id','lexiang_meal_company.company_name','lexiang_meal_company.company_id','lexiang_meal_shop.shop_tel')
        ->orderBy('lexiang_extract.insert_time','desc')
        ->paginate($page,['shopid','order-page','cate-page'],'extract-page');
    }
    
    /**
     * 用户提现总额
     */
    public function userExtractAccount($userid=false):int
    {
        return Extract::where('lexiang_extract.users_id',$userid)->sum('lexiang_extract.amount');
    }

    public function submitApplic($createData)
    {
        $nowtime = time();
        $createData['insert_time'] = $nowtime;
        return self::create($createData);
    }
}
